﻿using Furion.DependencyInjection;
using Furion.LinqBuilder;
using log4net;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Modules.ActionRun;
using Modules.Units;
using Newtonsoft.Json;
using RabbitMQ.Client;
using Sorting.App.Models;
using Sorting.App.Models.Entity;
using Sorting.App.Models.Enum;
using Sorting.App.Services;
using System;
using System.ComponentModel.Design;
using VOL.RabbitMq.IRabbitMq;
using VOL.RabbitMq.RabbitMq;
using VOL.RabbitMq.RabbitMqDto;

namespace SortingWorkerService.Handler
{
    /// <summary>
    /// 机器人消息数据处理器
    /// </summary>
    public class RabbitMqMessageHandler : BaseHandler, IRabbitMqMessageHandler, ITransient
    {
        #region 变量

        #endregion

        #region 属性

        /// <summary>
        /// 描述
        /// </summary>
        public override string Description => "机器人消息数据处理器";

        private ILog log = LogManager.GetLogger(typeof(RabbitMqMessageHandler));

        #endregion

        #region 构造函数
        private object _lockObj = new object();
        private RabbitMqClient _rabbitMqClient;
        private ShelfService shelfService = new ShelfService();
        private WardAreaService WardAreaService = new WardAreaService();
        private TaskLogService _logService = new TaskLogService();
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="serviceProvider">服务提供者</param>
        public RabbitMqMessageHandler(IServiceProvider serviceProvider, RabbitMqClient rabbitMqClient) : base(serviceProvider)
        {
            _rabbitMqClient = rabbitMqClient;
        }

        #endregion

        #region 接口实现
        /// <summary>
        /// 主题负载异步处理器
        /// </summary>
        /// <param name="client">MQTT客户端</param>
        /// <param name="topic">订阅主题</param>
        /// <param name="payloadContent">负载内容</param>
        /// <param name="isSys">是否系统</param>
        /// <returns></returns>
        public async Task<bool> TopicPayloadAsyncHandler(IModel client, string ExchangeName, string queuename, string payloadContent)
        {
            try
            {

                switch (queuename)
                {

                    case "SortingView.StartStopTask":

                        //AppsettingUnits.PutCount = 0;
                        //AppsettingUnits.ScanCount = 0;

                        var ms = JsonConvert.DeserializeObject<RabbitSendDto<bool>>(payloadContent);
                        Appsetting.IsStartPlcOrSoftWareLife = ms.TaskData;
                        await Task.Delay(50);
                        Appsetting.IsStartListingInPoint = ms.TaskData;
                        await Task.Delay(50);
                        Appsetting.IsStartListingScan = ms.TaskData;
                        await Task.Delay(50);
                       
                        if (ms.TaskMessage == "任务暂停")
                        {
                            ActionRunHelper.InBeltOff();
                            await Task.Delay(100);
                            ActionRunHelper.Stop();
                            log.Info("设备暂停任务成功" + DateTime.Now.ToString());
                            //await Task.Delay(50);

                        }
                        else
                        {
                         var re=   ms.TaskMessage.Split(',');
                            AppsettingUnits.UserName = re[1];
                           
                            ActionRunHelper.Start();
                            log.Info("设备启动任务成功" + DateTime.Now.ToString());
                            await Task.Delay(100);
                            log.Info("延迟" + DateTime.Now.ToString());
                            ActionRunHelper.InBeltOn();
                        }

                        break;
                   
                    case "SortingView.EquInitial":
                        log.Info("进入设备初始化" + DateTime.Now.ToString());
                        var backOrgState = await ActionRunHelper.GetbackOrgState();
                        if (AppsettingUnits.Appseeting.Initial)
                        {
                            if (backOrgState.Content[0] == 0)
                            {
                                ActionRunHelper.RunBackOrigin();
                            }
                            log.Info("设备初始化" + DateTime.Now.ToString());

                            while (backOrgState.Content[0] != 2)
                            {
                                backOrgState = await ActionRunHelper.GetbackOrgState();
                                await Task.Delay(100);
                            }
                        }
                        await Task.Delay(100);
                        //通知PLC初始化   设置模式、速度、回原点
                        ActionRunHelper.SelectPlcModelType(EnumPlcModelType.Auto); //选择模式
                        break;

                    case "Sorting.EndBagPoint":

                        //清楚放入队列已有队列信息
                        _rabbitMqClient.ClearAllMsg("Sorting", "Sorting.InBagPoint");

                        if (string.IsNullOrEmpty(Appsetting.ScanInfo.First()))
                        {
                            await _rabbitMqClient.PublishAsync("Sorting", "Sorting.SendToLoc", new RabbitSendDto<dynamic>
                            {
                                TaskType = "预备写入队列",
                                TaskData = "999",
                                TaskMessage = "预备写入队列，下发PLC"

                            });
                            return true;
                        }
                        else
                        {
                            await _rabbitMqClient.PublishAsync("Sorting", "Sorting.SendToLoc", new RabbitSendDto<dynamic>

                            {
                                TaskType = "预备写入队列",
                                TaskData = Appsetting.ScanInfo,
                                TaskMessage = "预备写入队列，下发PLC"

                            });
                        }
                        log.Info("最后一袋入队" + DateTime.Now.ToString());

                        break;

                    case "Sorting.SendToLoc":

                        //plc运动
                            if (AppsettingUnits.IsDown == 0)
                            {
                                AppsettingUnits.IsDown = 1;
                                log.Debug(JsonConvert.SerializeObject(payloadContent));
                                if (string.IsNullOrEmpty(payloadContent))
                                {
                                    return false;
                                }
                                var shelf = JsonConvert.DeserializeObject<RabbitSendDto<ShelfEntity>>(payloadContent).TaskData;

                                await _rabbitMqClient.PublishAsync("SortingView", "SortingView.PutCount", new RabbitSendDto<dynamic> //通知刷新界面
                                {
                                    TaskType = "任务执行中",
                                    TaskData = shelf.Uuid,
                                    TaskMessage = AppsettingUnits.TaskCount.ToString()
                                });
                                //分拣写入 plc
                               string Loc = shelf.LeftOrRight == "L" ? "1" : "2";
                               ActionRunHelper.RunToLoc((short)Convert.ToInt32(Loc+shelf.Row + shelf.Col)); //写入储位
                               log.Info(@$"任务下发PLC【{shelf.Name}】");

                            //写入完成后 消息通知界面处理
                                if (shelf.WardArea != "999")//NG位
                                    AppsettingUnits.TaskCount++;
                                shelf.State = EnumStockBoxState.Running;
                                 await _rabbitMqClient.PublishAsync("SortingView", "SortingView.SendFinish", new RabbitSendDto<dynamic>//更新已下发数量 刷新界面
                                {
                                    TaskType = "设备执行服务已经下发PLC",
                                    TaskData = shelf,
                                    TaskMessage = AppsettingUnits.TaskCount.ToString()
                                });       
                                //写入完成后 进入计数队列处理
                                await _rabbitMqClient.PublishAsync("Sorting", "Sorting.SendFinish", new RabbitSendDto<dynamic>//下发完成 更新库存
                                {
                                    TaskType = "计数队列处理",
                                    TaskData = shelf,
                                    TaskMessage = "计数队列处理，更新服务端库存"

                                });
                                AppsettingUnits.IsDown = 0;
                            }
                        
                        break;


                    //下发完成更新
                    case "Sorting.SendFinish":
                        Thread.Sleep(1000);
                        var data = JsonConvert.DeserializeObject<RabbitSendDto<ShelfEntity>>(payloadContent);
                        data.TaskData.Allstock++;

                        //库存满了关闭传送带 状态full
                        if (data.TaskData.Allstock >= data.TaskData.Max)
                        {
                            data.TaskData.State = EnumStockBoxState.Full;
                        }   
                        else
                        {
                            data.TaskData.State = EnumStockBoxState.NoFull;
                            
                        }
                            
                        await shelfService.UpdateShelfStore(data.TaskData);//更新库存
                        await WardAreaService.UpdateWardAreaState(data.TaskData.ScanInfo, AppsettingUnits.UserName);//更新分拣状态  state->1
                        //计数队列已经结束 消息通知界面处理  刷新界面
                        await _rabbitMqClient.PublishAsync("SortingView", "SortingView.CountFinish", new RabbitSendDto<dynamic>
                        {
                            TaskType = "计数队列已结束",
                            TaskData = data.TaskData,
                            TaskMessage = "计数队列已结束"
                        });
                        break;


                    case "Sorting.SendStartKeyout":
                        var keyout = JsonConvert.DeserializeObject<RabbitSendDto<dynamic>>(payloadContent);
                        if (keyout.TaskData == true)
                            ActionRunHelper.InBeltOn();
                        break;
                    default:
                        break;
                }



            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                return await Task.FromResult(false);
            }

            return await Task.FromResult(true);
        }



        #endregion

        #region 函数



        #endregion
    }
}
